package com.gxan.web.servlet.training;

import com.alibaba.fastjson.JSONObject;
import com.gxan.pojo.Training;
import com.gxan.service.TrainingService;
import com.gxan.service.impl.TrainingServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//按条件搜索培训计划
@WebServlet("/training/searchTraining")
public class SearchTrainingServlet extends HttpServlet {
    @Override
    public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");//设置返回结果的编码格式
        Map resultMap = new HashMap<>();//自定义map对象的方式返回结果给前端
        try {
            String training_name = request.getParameter("training_name");//得到培训名称
            String audit_status =request.getParameter("audit_status");//得到审核状态
            String start_time = request.getParameter("start_time");//得到开始时间
            String end_time = request.getParameter("end_time");//得到结束时间
            Integer page = Integer.parseInt(request.getParameter("page"));//得到当前页码数
            Integer limit = Integer.parseInt(request.getParameter("limit"));//得到每页显示多少条数
            TrainingService trainingService = new TrainingServiceImpl();
            List<Training> trainings = trainingService.searchTrainings(page,limit,training_name,audit_status,start_time,end_time);
            resultMap.put("code",0);
            resultMap.put("msg","查询成功");
            resultMap.put("count",trainingService.countTrainingByParams(training_name,audit_status,start_time,end_time));
            resultMap.put("data",trainings);
            response.getWriter().write(JSONObject.toJSONString(resultMap));
        }catch (Exception e){
            e.printStackTrace();
            resultMap.put("code",-1);
            resultMap.put("msg","系统出错了，请联系管理员!!!");
            //需要将Java对象转换为json字符串对象才能在网络中进行传输，把得到的集合对象转成json数据返回，以流的方式进行传输
            response.getWriter().write(JSONObject.toJSONString(resultMap));
        }
        response.getWriter().flush();//刷新流
        response.getWriter().close();//关闭流
    }
}
